package cn.edu.hqu.cst.android.add_service;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity  {
    private ICat catService;
    EditText et_first;
    EditText et_second;
    TextView  tv_result;


    private final ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            catService = ICat.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            catService = null;

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_first = findViewById(R.id.et_first);
        et_second = findViewById(R.id.et_second);
        tv_result = findViewById(R.id.tv_result);
        Intent intent = new Intent();
        intent.setAction("NumMath");
        intent.setPackage("cn.edu.hqu.cst.android.add_service");
        bindService(intent,conn,BIND_AUTO_CREATE);




    }


    @SuppressLint("SetTextI18n")
    public void add(View view){
        if (!TextUtils.isEmpty(et_first.getText().toString())&&!TextUtils.isEmpty(et_second.getText().toString())) {
            //获取输入框的值
            double num1=Double.parseDouble(et_first.getText().toString());
            double num2=Double.parseDouble(et_second.getText().toString());
            try {
                //通过服务对象来得到结果
                if(catService!=null){
                    double sum=catService.add(num1, num2);
                    //把结果显示在文本中
                    tv_result.setText(sum+" ");
                }else {
                    Toast.makeText(this,"服务没有启动！", Toast.LENGTH_SHORT).show();
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }


        }


    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unbindService(conn);
    }

}